<template>
    <div id="content">
        <div class="head-box">
            <div class="head-text">停车点树</div>
            <div>
                <template>
                    <template v-if="truckSpaceEditSign==1">
                        <a-button icon="plus" @click="addClick">新增车位</a-button>
                    </template>
                    <template v-if="truckSpaceEditSign==2">
                        <a-popconfirm title="确认删除？" okText="确认" cancelText="取消"
                                      @confirm="deleteClick" placement="topLeft">
                            <a-button icon="delete">删除车位</a-button>
                        </a-popconfirm>
                    </template>
                    <a-button icon="rollback" @click="rollbackClick">返回</a-button>
                </template>
            </div>
        </div>
        <div class="body-box">
            <div class="body-left">
                <template v-if="treeData.length > 0">
                    <a-directory-tree
                            :expandedKeys.sync="selectedKey"
                            :treeData="treeData"
                            :loadData="treeLoadData"
                            @expand="onExpand"
                            @select="onSelect"/>
                </template>
            </div>
            <div class="body-right">
                <template v-if="isShowTruckSpaceEditView">
                    <div class="box-item-truck">
                        <div class="right-item">
                            <div class="item-text">停车位编号</div>
                            <template>
                                <a-input style="width: 450px" v-model="inputTruckSpaceName"
                                         placeholder="停车位编号"/>
                            </template>
                        </div>
                        <div class="right-item">
                            <div class="item-text">设备序列号</div>
                            <template>
                                <a-input style="width: 450px" v-model="inputImei"
                                         placeholder="设备序列号"/>
                            </template>
                        </div>
                        <div class="right-item">
                            <div class="item-text">单目</div>
                            <template>
                                <label class="checkboxClass">
                                    <input type="checkbox" v-model="checkdeDirection" :value="11" @click="checkOneDirection"/>
                                    <span>左目</span>
                                </label>
                                <label class="checkboxClass">
                                    <input type="checkbox" v-model="checkdeDirection"  :value="12" @click="checkOneDirection"/>
                                    <span>右目</span>
                                </label>
                            </template>
                        </div>
                        <div class="right-item">
                            <div class="item-text">双目</div>
                            <template>
                                <label class="checkboxClass">
                                    <input type="checkbox" v-model="checkdeDirection" :value="21" @click="checkOneDirection"/>
                                    <span>左目</span>
                                </label>
                                <label class="checkboxClass">
                                    <input type="checkbox" v-model="checkdeDirection" :value="22" @click="checkOneDirection"/>
                                    <span>右目</span>
                                </label>
                            </template>
                        </div>
                        <div class="right-item">
                            <div class="item-text">经纬度</div>
                            <template>
                                <a-input style="width: 450px" v-model="inputLngAndLat"
                                         placeholder="经度在前，中文逗号隔开"/>

                                <div @click="selectMap" style="margin-left: 10px">
                                    <a-button>打开地图</a-button>
                                </div>
                            </template>
                        </div>
                        <a-button icon="save" @click="saveClick">保存</a-button>

                    </div>
                    <!--  -->
                    <div id="map">
                        <!-- 地图 -->
                        <div id="box-map"/>
                        <!-- 搜索框 -->
                        <div id="contain-tool" v-if="mapData.visible">
                            <div id="contain-search">
                                <!-- 输入框 -->
                                <input id="keyword"
                                       class="input-search"
                                       placeholder="搜索站点位置..."
                                       maxlength="256"
                                />
                                <!-- 搜索icon -->
                                <img class="icon-search" src="../../images/icon/search.png"/>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

    </div>
</template>

<script>
    import ParkApi from '../../api/system/ParkApi';
    import TruckSpaceApi from '../../api/system/TruckSpaceApi';
    const queryCondition = {id: ""};
    const addAndEditCondition = {
        id: "",
        parkId: "",
        truckSpaceName: "",
        imei: "",
        longitude: "",
        latitude: "",
        direction: "",
    };
    const deleteCondition = {id: ""};

    /* 地图 */
    const marker = new AMap.Marker();

    export default {
        name: "TruckSpaceEdit.vue",

        data() {
            return {
                /**停车点树**/
                treeData: [],
                selectedKey: [],
                queryCondition,
                addAndEditCondition,
                deleteCondition,
                /**其他**/
                inputTruckSpaceName: "",
                inputImei: "",
                inputLngAndLat: "",
                checkdeDirection: [],
                lng: "",
                lat: "",
                showTruckSpaceEditView: false,
                //车位编辑按钮状态，0初始化，1新增，2删除
                truckSpaceEditSign: 0,
                selectedTruckSpaceId: "",
                selectTruckSpaceNode: undefined,
                selectParkNode: undefined,
                /* 地图 */
                marker,
                mapData: {
                    visible: false,
                    lng: "",
                    lat: "",
                }
            }
        },

        methods: {
            /* -------------------- 初始化数据 -------------------- */
            initParkTreeData() {
                ParkApi.parkTree().then((data) => {
                        let tree = data.data;
                        /* 处理key */
                        this.dealCreateKey(tree, 'T');
                        /* 处理id */
                        if(this.selectedKey.length > 0) {
                            this.selectedKey = [this.getTreeKey(tree, this.selectedKey[0])];
                        }
                        console.log(tree)
                        this.treeData = tree;
                    }).catch((err) => {
                        console.log(err)
                        this.$message.error("获取停车点树数据异常！");
                    });
            },

            treeLoadData(node) {
                console.log(node)
                return new Promise((resolve) => {
                    if (node.dataRef.children) {
                        resolve();
                        return
                    }

                    // let expanded = node.expanded;
                    let key = node.eventKey.split(',')[1];
                    // if (expanded) return;
                    if (isNaN(key)) return;

                    let condition = this.queryCondition;


                    condition.id = key;
                    // let selectNode = node;

                    TruckSpaceApi.list(condition)
                        .then((data) => {
                            if (data.data == null) {
                                resolve();
                                return;
                            }
                            node.dataRef.children = data.data.truckSpaceModelList;
                            this.treeData = [...this.treeData];
                            resolve();
                        })
                        .catch(err => {
                            console.log("查询车位列表异常！", err);
                        });
                });


            },

            dealCreateKey(array, name) {
                // let newArray = [];
                if(!array || array.length == 0) return ;
                let len = array.length;
                for(let i = 0; i < len; i++) {
                    console.log(array[i])
                    if(array[i]){
                        if(array[i].type!= 2){
                            array[i].key = name + '-' + i;
                            if(array[i].id) {
                                array[i].key = array[i].key + "," + array[i].id
                            }
                            this.dealCreateKey(array[i].children, array[i].key);
                        }else{
                            //停车场没有车位，这里不显示
                            console.log("删除")
                            array.splice(i, 1);
                            i=i-1;
                        }
                    }
                }
            },

            getTreeKey(array, id) {
                if(!array || array.length == 0) return ;
                let len = array.length;
                for(let i = 0; i < len; i++) {
                    if(array[i].id == id) return array[i].key;
                    let value = this.getTreeKey(array[i].children, id);
                    if(value) return value;
                }
                return "";
            },

            /* -------------------- 树上事件 -------------------- */
            onExpand() {
            },

            onSelect(selectedKeys, e) {
                console.log(selectedKeys)
                //树节点有key，但不是叶子节点则表明该节点为停车点
                //树节点有key，是叶子节点则表明该节点为车位
                this.clearTreeSelectData();
                // let leaf = e.node.isLeaf;

                // T-O-0
                // T-0-0, id
                // id
                let key = selectedKeys[0] + "";                
                let array = key.split(',');
                
                /* 支点 */
                if(array.length == 2) {
                    this.truckSpaceEditSign = 1;
                    this.selectParkNode = e.node;
                    return ;
                }

                /* 判断是否是数字 */
                if (isNaN(array[0])) {
                    return;
                }

                /* 叶子的时候 */
                this.showTruckSpaceEditView = true;
                this.truckSpaceEditSign = 2;
                this.selectedTruckSpaceId = key;
                this.selectTruckSpaceNode = e.node;

                let lng = e.node.dataRef.lng;
                let lat = e.node.dataRef.lat;
                this.lng = lng;
                this.lat = lat;
                this.checkdeDirection=[e.node.dataRef.direction];
                this.inputImei = e.node.dataRef.imei;
                this.inputTruckSpaceName = e.node.dataRef.truckSpaceName;
                if (!this.stringIsBlank(lng) && !this.stringIsBlank(lat)) {
                    this.inputLngAndLat = lng + "，" + lat;
                }
                if (this.mapControl) {
                    this.initMap();
                }

            },

            /* -------------------- 界面事件 -------------------- */
            addClick() {
                let selectParkNode = this.selectParkNode;
                if (this.stringIsBlank(selectParkNode)) {
                    return this.$message.warn("请选择停车点！");
                }
                let parkId = selectParkNode.dataRef.id;
                let condition = this.addAndEditCondition;
                condition.parkId = parkId;
                let that = this;

                TruckSpaceApi.addTruckSpace(condition).then((data) => {
                    let dataPush = data.data;
                    dataPush.key = dataPush.id;
                    dataPush.title = dataPush.truckSpaceName;
                    dataPush.isLeaf = true;
                    let children = that.selectParkNode.dataRef.children;
                    if (children == undefined) {
                        that.selectParkNode.dataRef.children = [];
                    }
                    children.push(dataPush);
                    // this.clearTreeSelectData();
                }).catch(err => {
                    console.log("新增停车位异常！", err);
                });
            },

            deleteClick() {
                let truckSpaceId = this.selectedTruckSpaceId;
                if (isNaN(truckSpaceId)) {
                    return this.$message.warn("请选择删除的车位！");
                }

                let condition = this.deleteCondition;
                condition.id = truckSpaceId;
                TruckSpaceApi.delTruckSpace(condition)
                    .then(() => {
                        this.clearTreeSelectData();
                        //本地删除
                        let filter = this.selectTruckSpaceNode.$parent.dataRef.children.filter(function (item) {
                            return item.id != truckSpaceId;
                        });
                        this.selectTruckSpaceNode.$parent.dataRef.children = filter;
                        this.selectTruckSpaceNode = undefined;
                        this.$message.success("删除成功！");
                    })
                    .catch(err => {
                        let data = err.data;
                        let msg = err.msg;
                        this.$message.warn(data || msg);
                    });

            },
            saveClick() {
                let lng = "";
                let lat = ""
                let inputImei = this.inputImei;
                let inputTruckSpaceName = this.inputTruckSpaceName;
                let direction = this.checkdeDirection[0] === undefined ?0:this.checkdeDirection[0];
                let selectedTruckSpaceId = this.selectedTruckSpaceId;
                let inputLngAndLat = this.inputLngAndLat;
                if (!this.stringIsBlank(inputLngAndLat)) {
                    let split = inputLngAndLat.split("，");
                    if (split == undefined) {
                        return this.$message.warn("经纬度不规范！");
                    }
                    lng = split[0];
                    lat = split[1];
                    let boolLng = this.checkLong(lng);
                    let boolLat = this.checkLat(lat);
                    // if (boolLng && boolLat) {
                    // } else {
                        if(!boolLng || !boolLat){
                        return this.$message.warn("经纬度不规范");
                    }

                }
                let condition = this.addAndEditCondition;
                condition.id = selectedTruckSpaceId;
                condition.parkId = this.selectTruckSpaceNode.dataRef.parkId;
                condition.imei = inputImei;
                condition.longitude = lng;
                condition.latitude = lat;
                condition.truckSpaceName = inputTruckSpaceName;
                condition.direction = direction;

                TruckSpaceApi.updateTruckSpace(condition).then(() => {
                    this.selectTruckSpaceNode.dataRef.imei = inputImei;
                    this.selectTruckSpaceNode.dataRef.truckSpaceName = inputTruckSpaceName;
                    this.selectTruckSpaceNode.dataRef.title = inputTruckSpaceName;
                    this.selectTruckSpaceNode.dataRef.lat = lat;
                    this.selectTruckSpaceNode.dataRef.lng = lng;
                    this.selectTruckSpaceNode.dataRef.direction = direction;
                    this.$message.success("修改成功！");
                }).catch(err => {
                    let data = err.data;
                    let msg = err.msg;
                    if (data) {
                        return this.$message.warn(data);
                    }
                    if (msg) {
                        return this.$message.warn(data);
                    }
                    console.log("保存车位信息异常！", err);
                });

            },

            rollbackClick() {
                this.$router.push('/system/parkingLot');
            },

            /* -------------------- 工具类 -------------------- */
            checkLong(lng) {
                // let longrg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
                let longrg = /^(-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
                if (!longrg.test(lng)) {
                    return false;
                }
                return true;
            },

            checkLat(lat) {
                // let latreg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
                 let latreg = /^(-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
                if (!latreg.test(lat)) {
                    return false;
                }
                return true;
            },

            stringIsBlank(str) {
                if (str == undefined || str == '') {
                    return true;
                }
                return false;
            },

            clearTreeSelectData() {
                this.showTruckSpaceEditView = false;
                this.truckSpaceEditSign = 0;
                this.selectedTruckSpaceId = "";
                this.selectParkNode = undefined;
                this.lng = "";
                this.lat = "";
                this.inputLngAndLat = "";
                this.checkdeDirection = [];
            },

            /* -------------------- 地图 ---------------------- */
            selectMap() {
                this.initMap();
            },

            initMap() {
                this.destroyMap();
                let defaultLat = '22.547';
                let defaultLng = '114.085947';
                let selectlng = this.lng || defaultLng;
                let selectlat = this.lat || defaultLat;
                this.mapData = {lng: selectlng, lat: selectlat, visible: true}
                let {lng, lat} = this.mapData;
                if (!this.mapControl) {
                    this.mapControl = new AMap.Map("box-map", {
                        zoom: 16,
                        center: [lng, lat],
                        viewMode: "3D",
                        resizeEnable: true
                    });
                    this.mapControl.on("click", this.mapClick);
                    this.mapControl.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => this.pluginCallback());
                }
                this.mapControl.setCenter([lng, lat])
                this.drawMarker({lng, lat})
            },

            destroyMap() {
                this.mapControl && this.mapControl.destroy();
                this.mapControl = undefined;
            },

            mapClick(e) {
                this.drawMarker(e.lnglat)
                let {lat, lng} = e.lnglat;
                this.lng = lng, this.lat = lat;
                this.inputLngAndLat = lng + "，" + lat;
            },

            drawMarker({lat, lng}) {
                let lnglat = new AMap.LngLat(lng, lat);
                /* 生成 */
                this.mapControl.add(this.marker);
                marker.setPosition(lnglat);
            },

            pluginCallback() {
                let autoOptions = {
                    city: "北京", //城市，默认全国
                    input: "keyword"//使用联想输入的input的id
                };

                let autocomplete = new AMap.Autocomplete(autoOptions);
                let placeSearch = new AMap.PlaceSearch({
                    city: '北京',
                    map: this.mapControl,
                });

                AMap.event.addListener(autocomplete, "select", (e) => {
                    placeSearch.setCity(e.poi.adcode);
                    placeSearch.search(e.poi.name, (status, result) => this.placeSearchCallBack(status, result));
                });
            },

            placeSearchCallBack(status, result) {
                if (status == 'complete') {
                    let count = result.poiList.count;
                    if (count > 0) {
                        let pois = result.poiList.pois[0];
                        let location = pois.location;
                        let lng = location.lng;
                        let lat = location.lat;
                        this.mapControl.setCenter([lng, lat]); //设置地图中心点
                        //清除所有覆盖物！
                        // result.poiList = [];
                        this.mapControl.clearMap();
                    }
                } else if (status == 'error') {
                    console.error("搜索失败！");
                } else if (status == 'no_data') {
                    console.log("无搜索结果");
                } else {
                    console.log("未知！");
                }
            },
            checkOneDirection(event)  {
                if ($(event.target).prop("checked") === false) {
                    this.checkdeDirection=[];
                } else {  //判断当前对象为选中状态
                    this.checkdeDirection=[$(event.target).val()];
                }
            },
        },

        mounted() {
            if (this.$route.query.id) {
                this.selectedKey = [this.$route.query.id];
            } else {
                this.selectedKey = []
            }
            this.initParkTreeData();
        },
        computed: {
            isShowTruckSpaceEditView() {
                return this.showTruckSpaceEditView;
            }
        },
    }


</script>

<style scoped>
    #content {
        width: 100%;
        height: 100%;
    }

    .head-box {
        display: flex;
        justify-content: space-between;
        border-bottom: #e8e2e2 0.5px solid;
    }

    .head-box .head-text {
        padding: 10px 20px;
    }

    .head-box button {
        margin: 10px 20px;
    }


    .body-box {
        display: flex;
        width: 100%;
        height: 100%;
    }

    .body-left {
        width: 30%;
        border-right: #e8e2e2 0.5px solid;
        overflow: scroll;
    }

    .body-right {
        position: relative;
        width: 70%;
    }

    .box-item-truck {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .body-right .right-item {
        width: 700px;
        display: flex;
        /* justify-content: center; */
        align-items: center;
        margin: 10px;
    }

    .right-item .item-text {
        width: 200px;
    }

    .right-item input {
        width: 200px;
    }

    /* -------------------- 地图 -------------------- */
    #map {
        position: absolute;
        left: 50%;
        transform: translate(-50%, 0);
        width: 80%;
        height: 600px;
    }

    #box-map {
        width: 100%;
        height: 100%;
    }

    #contain-tool {
        position: absolute;
        top: 24px;
        z-index: 100;
        /*left: 770px;*/
    }

    #contain-search {
        width: 240px;
        height: 40px;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0px 1px 10px 0px rgba(201, 201, 201, 1);
        /* flex */
        display: flex;
        align-items: center;
        margin-left: 10px;
    }

    #contain-search .input-search {
        margin-left: 25px;
        flex: 1 1 auto;
        border: none;
        height: 100%;
        outline: none;
        /* text */
        font-size: 16px;
        color: #020202;
    }

    #contain-search .input-clear {
        cursor: pointer;
        width: 27px;
        height: 38px;
        background: url(//webmap1.bdimg.com/wolfman/static/common/images/new/searchbox_5c0d97d.png) no-repeat 0 -114px #fff;
    }

    #contain-search .icon-search {
        width: 20px;
        height: 20px;

        margin-left: 10px;
        margin-right: 25px;
        cursor: pointer;
    }
    .checkboxClass{
        width: 25%;
    }
    .checkboxClass input{
        width: 20%;
    }
    .checkboxClass span{
        text-indent : 10px;
        letter-spacing: 12px;
    }
</style>
